# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from django.contrib.admin.models import User
from django.db.models import Q
from django.http import HttpResponse, HttpResponseNotModified
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getCompanyTuple
from website.constant import VALID_LOGIN_STATE, DEFAULT_PWD
from website.models import Menu
from website.usercontrol.models import SysUser, SysRole, SysLoginLog, \
    IndexRecord
import datetime


@csrf_exempt
def sysuser_login(request):
    login_ip=request.META['REMOTE_ADDR']
    login_name=request.POST.get('login_name','')
    login_pwd=request.POST.get('login_pwd','')
    try:
        CurrentUser=SysUser.objects.get(login_name=login_name,login_pwd=login_pwd)
        if CurrentUser.login_state==VALID_LOGIN_STATE:
            request.session['CurrentUser'] = CurrentUser
            #记录日志
            try:
                companyId=getCompanyTuple(request)[0]
                SysLoginLog.objects.create(login_name=login_name,login_ip=login_ip,employe_id=CurrentUser.employe.id,company_id=companyId)
            except Exception:
                SysLoginLog.objects.create(login_name=login_name,login_ip=login_ip)
#                return HttpResponse(dumps({'success':False,'message':'无法获取该帐号所属校区！'}))
        else:
            return HttpResponse(dumps({'success':False,'message':'该帐号已失效！'}))
    except Exception:
        return HttpResponse(dumps({'success':False,'message':'用户名或密码错误！'}))
    return HttpResponse(dumps({'success':True}))

#系统登录用户管理
@csrf_exempt
def sysuser_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    login_name=request.POST.get('login_name','')
    if login_name is not '':
        queryset=SysUser.objects.filter(login_name__icontains=login_name)
    else:
        queryset=SysUser.objects.all()
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','login_name','login_last','login_state',
             'role__id','role__role_name','create_time','mac','ip','employe__id','employe__name')),queryset.count()))


@csrf_exempt
def sysuser_save(request):
    try:
        sysuser_id=request.POST.get('id','')
        login_name=request.POST.get('login_name','')
        login_pwd=request.POST.get('login_pwd','')
        login_state=request.POST.get('login_state',0)
        role_id=request.POST.get('role__id',None)
        mac=request.POST.get('mac',None)
        ip=request.POST.get('ip',None)
        employe_id=request.POST.get('employe__id',None)
        if sysuser_id=='':
            existUser=SysUser.objects.filter(login_name=login_name)
            if(existUser):
                return HttpResponse(dumps({'success':False,'message':'用户名已存在请更换用户名！'}))
            SysUser.objects.create(login_name=login_name,login_pwd=login_pwd,login_state=login_state,role_id=role_id,
                                   mac=mac,ip=ip,employe_id=employe_id)
        else:
            sysuser=SysUser.objects.get(id=sysuser_id)
            sysuser.login_name=login_name
            #sysuser.login_pwd=login_pwd
            sysuser.login_state=login_state
            sysuser.role_id=role_id
            sysuser.mac=mac
            sysuser.ip=ip
            sysuser.employe_id=employe_id
            sysuser.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def sysuser_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids is not '':
            sysuser_ids=ids.split(',')
            for sysuser_id in sysuser_ids:
                SysUser.objects.get(id=sysuser_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))  

@csrf_exempt
def sysuser_pwd_reset(request):
    # 重置密码
    try:
        sysuser_id=request.POST.get('id','')
        
        sysuser=SysUser.objects.get(id=sysuser_id)
        sysuser.login_pwd=DEFAULT_PWD
        sysuser.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def sysuser_change_pwd(request):
    # 密码修改
    try:
        old_password=request.POST.get('old_password','')
        confirm_password=request.POST.get('confirm_password','')
        CurrentUser=request.session.get('CurrentUser')
        if(CurrentUser.login_pwd==old_password):
            sysuser=SysUser.objects.get(login_name=CurrentUser.login_name,login_pwd=CurrentUser.login_pwd)
            sysuser.login_pwd=confirm_password
            sysuser.save()
        else:
            return HttpResponse(dumps({'success':False,'message':'原密码错误！'}))
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'修改密码成功！'}))

#系统登录角色管理
@csrf_exempt
def sysrole_list(request):
    queryset=SysRole.objects.all()
    sysrole_tree=[]
    for item in queryset:
        sysrole_node={}
        sysrole_node['id']=item.id
        sysrole_node['text']=item.role_name
        sysrole_node['leaf']=True
        sysrole_tree.append(sysrole_node)
    return utils.JsonResponse(utils.JSONserialise(sysrole_tree))


@csrf_exempt
def sysrole_save(request):
    try:
        sysrole_id=request.POST.get('id','')
        role_name=request.POST.get('role_name','')
        if sysrole_id =='':
            SysRole.objects.create(role_name=role_name)
        else:
            sysrole=SysRole.objects.get(id=sysrole_id)
            sysrole.role_name=role_name
            sysrole.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def sysrole_del(request):
    try:
        sysrole_id=request.POST.get('id','')
        if sysrole_id is not '':
            sysrole=SysRole.objects.get(id=sysrole_id)
            sysrole.sysuser_role.all().update(role=None)
            sysrole.delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))  

@csrf_exempt
def sysrole_authority_list(request):
    try:
        role_id=request.POST.get('role_id','')
        role_menu=SysRole.objects.get(id=role_id).role_menu.all()
    except:
        role_menu=None
    
    menus=Menu.objects.all()
    nodes=[]
    for item in menus:
        node={}
        node['id']=item.id
        node['text']=item.name
        node['leaf']=item.is_leaf
        node['parent_id']=item.parent_id
        if role_menu is not None and  item in role_menu :
            node['checked']=True
        else:
            node['checked']=False
        nodes.append(node)
        
    for childrenNode in nodes:
        for parentNode in nodes:
            if childrenNode['parent_id'] == parentNode['id']:
                parentNode['expanded']=True
                try:
                    parentNode['children'].append(childrenNode)
                except KeyError:
                    parentNode['children']=[]
                    parentNode['children'].append(childrenNode)
    data=[]
    for node in nodes:
        if node['parent_id']==None :
            data.append(node)
    return HttpResponse(dumps(data))   

@csrf_exempt
def sysrole_authority_save(request):
    try:
        role_id=request.POST.get('role_id','')
        ids=request.POST.get('ids','')
        if role_id is not None and ids is not None:
            sysrole=SysRole.objects.get(id=role_id)
            sysrole.role_menu.clear()
            menu_ids=ids.split(',')
            for menu_id in menu_ids:
                sysrole.role_menu.add(Menu.objects.get(id=menu_id))
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'权限保存成功！'})) 



#登录日志查询
@csrf_exempt
def syslogin_log_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    login_name=request.POST.get('login_name','')
    start_day=request.POST.get('start_day','')
    start_time=request.POST.get('start_time','')
    end_day=request.POST.get('end_day',datetime.datetime.now().strftime('%Y-%m-%d'))
    end_time=request.POST.get('end_time',datetime.datetime.now().strftime('%H:%M'))
    
    q=Q(login_time__lte=end_day+' '+end_time)
    if start_day <>'' and start_time <> '':
        q&= Q(login_time__gte=start_day+' '+start_time)
    if login_name <> '':
        q&= Q(login_name__icontains=login_name) 
    queryset=SysLoginLog.objects.filter(q)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','login_time','login_name','company__cn_name',
            'employe__name','login_ip')),queryset.count()))
    

#系统首页记录展示列表(个人)
@csrf_exempt
def index_display_list(request):
    try:
        available_queryset=IndexRecord.objects.all()
        CurrentUser=request.session.get('CurrentUser')
        selected_queryset=CurrentUser.index_record.all()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)})) 
    return HttpResponse(dumps({'success':True,
        'available':list(available_queryset.values('id','text')),'selected':list(selected_queryset.values_list('id'))}))

#系统首页记录展示保存
@csrf_exempt
def index_display_save(request):
    indexform=request.POST.get('indexform','')
    try:
        CurrentUser=request.session.get('CurrentUser')
        CurrentUser.index_record.clear()
        records=indexform.split(',')
        for record in records:
            CurrentUser.index_record.add(IndexRecord.objects.get(id=record))
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':'true','message':'设置保存成功将在下次登录生效！'}))